from zope.interface import implements
from twisted.internet import defer
from twisted.web2 import stream as stream_mod

class SniffProxyStream(object):
    implements(stream_mod.IByteStream)

    #IByteStream
    length = None

    #sniffed data
    data = None

    def __init__(self, stream):
        self._stream = stream
        self.length  = stream.length
        self.data    = ''

    #IByteStream
    def split(self, point):
        return stream_mod.fallbackSplit(self, point)

    #IByteStream
    def read(self):
        if not hasattr(self, '_stream'):
            #after close()
            return None

        data = self._stream.read()
        if data is None:
            return None
        elif isinstance(data, defer.Deferred):
            def _append(self, data):
                self.data += str(data)
            data.addCallback(self._append)
        else:
            self.data += str(data)
        return data

    #IByteStream
    def close(self):
        self._stream.close()
        del self._stream

__all__ = [
    'SniffProxyStream',
]
